<template>
<div class="table-wrap">
    <common-table :tableHead="tableHead" :data="tableData" :limit="10" :pagination="pagination" @operate="operate" @turnPage="search">
      <template slot="globalOperate">
        <el-button class="small_btn" type="text" @click.stop="openModel()"><i class="el-icon-plus"></i><span class="font-color">{{$t('public.add')}}</span ></el-button>
      </template>
    </common-table>
    <el-drawer
			:visible="visible"
			direction="rtl"
      :wrapperClosable="false"
      size="600px"
			:before-close="handleClose">
      <span slot="title" class="title">{{this.form._id ? this.$t('public.edit2') : this.$t('public.add')}}{{$t('configLazyLoad.emailNotify.notificationMailTemplate')}}</span>
			<div class="form-wrap">
				<el-form 
					ref="form"
					:model="form"
					size="small"
					:rules="rules">
				<el-form-item prop="name" :label="$t('configLazyLoad.emailNotify.templateName')">
					<el-input type="text" v-model="form.name" :maxlength="30" :placeholder="$t('configLazyLoad.emailNotify.plaholderTip')"/>
				</el-form-item>
				<el-form-item prop="subject" :label="$t('configLazyLoad.emailNotify.emailSubject')">
					<el-input type="text" v-model="form.subject" :maxlength="50" :placeholder="$t('configLazyLoad.emailNotify.plaholderTip1')"/>
				</el-form-item>
				<el-form-item prop="content" :label="$t('configLazyLoad.emailNotify.emailBody')">
          <br>
          <div id="mail_notify_template">
          </div>
				</el-form-item>
           <div class="message">
            <span class="message-title">{{$t('configLazyLoad.businessConfig.placeholderTip')}}:</span><br>
            {{$t('business.businessNumber')}}:{ticket.field_num}<br> 
            {{$t('config.business.triggerHeading')}}:{task_name} <br>
            {{$t('business.businessFlow')}}：{ticket.flow} <br>
            {{$t('business.priorityLabel')}}：{ticket.priority} <br>
            {{$t('business.businessCreate')}}：{ticket.create_user} <br>
            {{$t('business.businessCreateTime')}}：{ticket.create_time} <br>
            {{$t('business.businessOverallInformation')}}：{ticket.full_detail}<br>
          </div>
			</el-form>
			</div>
				<div class="footer">
					<el-button class="primary_btn" @click="handleClose">{{$t('public.cancel')}}</el-button>
					<el-button class="primary_btn" type="primary" @click="save">{{$t('public.save')}}</el-button>
				</div>
		</el-drawer>
  </div>
</template>
<script>
  import CommonTable from '../../config/robotConfig/base/CommonTable.vue'
  import {filterXSS} from '@/utils/m7Utils'
  import API from '../../../../store/api/config/emailNotify.js'
  import {cloneDeep} from 'lodash'
  import Editor from 'wangeditor'
  const baseForm = {
          name: '',//模板名称
          subject: '',//主题
          content: ''//内容
        }
  export default {
    name: 'MailTemplate',
    data () {
      return {
        visible: false,
        pagination: {
          currentPage: 0,
          count: 0,
          totalPage: 0
        },
        searchObj: {
          page: 1,
          limit: 10
        },
        form: {
          name: '',//模板名称
          subject: '',//主题
          content: ''//内容
        },
        rules: {
          name: [
            {required: true, message: this.$t('validate.required'), trigger: 'blur'}
          ],
          subject: [
            {required: true, message: this.$t('validate.required'), trigger: 'blur'}
          ],
          content: [
            {required: true, message: this.$t('validate.required'), trigger: 'blur'}
          ]
        },
        tableData: [],
        tableHead: [
          {prop: 'name', label: this.$t('configLazyLoad.emailNotify.templateName')},
          {prop: 'createTime', label: this.$t('public.createTime')},
          {prop: 'updateTime', label: this.$t('public.updateTime')},
          {prop: 'operate', label: this.$t('public.operate'), special: 'operate', operate: [{name: this.$t('public.edit2'), type: 'edit'}, {name: this.$t('public.delete'), type: 'delete', class: 'delete'}]}
        ],
        exportType: this.$store.state.isRealTimeExport ? 'real' : '' // real实时导出任务
      }
    },
    components: {
      CommonTable
    },
    methods: {
      operate (event) {
        let type = event.type
        let data = event.val
        if (type === 'delete') {
          this.delete({_id: data._id})
        } else if (type === 'edit') {
          this.edit(data)
        }
      },
      edit (data) {
        API.queryEmailTemplateById({_id: data._id}).then((res) => {
          if (res.success) {
            this.openModel(res.data)
          }
        })
      },
      openModel (item) {
        this.form = cloneDeep(baseForm)
        this.visible = true
        this.$nextTick(() => {
          this.initEditor()
          if (item) {
            for (let i in this.form) {
              this.form[i] = item[i]
            }
            this.form._id = item._id
            this.form.content = filterXSS(this.form.content)
          }
          this.wEditor.txt.html(this.form.content)
          this.$refs.form.clearValidate()
        })
      },
      delete ({_id}) {
        this.$confirm(this.$t('business.businessDeleteTip'), this.$t('public.delete'), {
          confirmButtonText: this.$t('public.confirm'),
          cancelButtonText: this.$t('public.cancel'),
          cancelButtonClass: 'primary_btn',
          confirmButtonClass: 'primary_btn',
          type: 'warning'
        })
          .then(() => {
            API.deleteEmailTemplateById({_id})
              .then(resp => {
                if (resp.success) {
                  this.search()
                  this.$message({
                    type: 'success',
                    message: this.$t('message.deleteSucc')
                  })
                }
              })
          })
      },
      search (page) {
        this.searchObj.page = typeof page === 'number' ? page : 1
        API.queryEmailTemplateList(this.searchObj).then((res) => {
          this.tableData = []
          if (res.success) {
            // let sessionId = this.$store.state.session.sessionId
            this.pagination.count = res.count
            this.pagination.currentPage = this.searchObj.page
            let list = res.data || []
            this.tableData = list
          }
        })
      },
      handleClose () {
				this.visible = false
			},
      save () {
				this.$refs.form.validate((valid) => {
          if (valid) {
            //给后端传当前语言
            this.form.lang = window.localStorage.getItem('lang')
            // table加border
            this.form.content = this.form.content.replace(/<table border="0" width="100%" cellpadding="0" cellspacing="0">/g, '<table style="width:100%;" cellpadding="2" cellspacing="0" border="1" bordercolor="#262626">')
						API.editEmailTemplate(this.form).then((res) => {
              this.$message.success(this.$t('business.operateSuc'))
              this.handleClose()
              this.search()
						})
          }
        })
      },
      initEditor () {
        if (this.wEditor) {
          return
        }
        this.wEditor = new Editor('#mail_notify_template')
        this.wEditor.config.menus = [
          'head',  // 标题
          'bold',  // 粗体
          'fontSize',  // 字号
          'fontName',  // 字体
          'italic',  // 斜体
          'underline',  // 下划线
          'strikeThrough',  // 删除线
          'foreColor',  // 文字颜色
          'backColor',  // 背景颜色
          'link',  // 插入链接
          'list',  // 列表
          'justify',  // 对齐方式
//          'quote',  // 引用
//          'emoticon',  // 表情
          'table',  // 表格
          // 'code',  // 插入代码
          'undo',  // 撤销
          'redo'  // 重复
        ]
        // 粘贴，自定义过滤
        this.wEditor.config.pasteTextHandle = filterXSS
        this.wEditor.config.fontNames = [ '微软雅黑', '宋体', '新宋体', '仿宋', '楷体', '黑体', 'Arial', 'Arial Black', 'Times New Roman', 'Courier New', 'Tahoma', 'Verdana' ]
        this.wEditor.config.onchange = (html) => {
          this.form.content = this.wEditor.txt.html()
        }
        this.wEditor.config.zIndex = 100
        this.wEditor.create()
      }
    },
    beforeMount () {
      this.search()
    },
    beforeRouteLeave (to, from, next) {
      if (this.visible) {
        this.$confirm(this.$t('business.giveUpTip'), this.$t('business.giveUpSure'), {
          confirmButtonText: this.$t('public.confirm'),
          cancelButtonText: this.$t('public.cancel'),
          cancelButtonClass: 'primary_btn',
          confirmButtonClass: 'primary_btn',
          type: 'warning'
        })
          .then(() => {
            this.handleClose()
            next() 
          })
      } else {
        next() 
      }
    }
  }
</script>
<style lang="stylus">
#mail_notify_template
  .w-e-menu
    line-height 18px
  .w-e-text-container
    height 200px!important
</style>
<style lang="stylus" scoped>
  @import "../../../../assets/common.styl"
  .table-wrap
    padding 20px 5px
    box-sizing border-box
  .form-wrap
    padding 0 20px
    box-sizing border-box
    height calc(100vh - 128px)
    overflow-y auto
  .footer
    position absolute
    bottom 0
    right 0	
    box-sizing border-box
    width 100%
    border-top 1px solid #efefef
    height 50px
    text-align center
    padding-top 13px
  .message
    background-color #f6f6f6
    padding 12px
    font-size 12px
    line-height 20px
    margin-top 10px
    .message-title
      color #424242
</style>